﻿/// ******************************************************************
///  AUTHOR: Daniel S. Soper
///     URL: http://www.danielsoper.com
///    DATE: 20 February 2007
/// LICENSE: Public Domain. Enjoy!   :-)
/// ******************************************************************

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.ComponentModel;

namespace AppFx.DevControls
{
	public class NumberedDataGridView : DataGridView
	{
		/// <summary>
		/// Gibt oder setzt ob die Zeilen nummeriert angezeigt werden sollen.
		/// </summary>
		[DefaultValue(true)]
		public bool Numbered { get; set; }

		/// <summary>
		/// Erstellt eine neue Instanz der <see cref="NumberedDataGridView"/>-Klasse.
		/// </summary>
		public NumberedDataGridView()
		{
			Numbered = true;
			AlternatingRowsDefaultCellStyle.BackColor = Color.LightGray;
		}

		/// <summary>
		/// Löst das <see cref="E:System.Windows.Forms.DataGridView.RowPostPaint"/>-Ereignis aus.
		/// </summary>
		/// <param name="e">Ein <see cref="T:System.Windows.Forms.DataGridViewRowPostPaintEventArgs"/>, das die Ereignisdaten enthält.</param>
		protected override void OnRowPostPaint(DataGridViewRowPostPaintEventArgs e)
		{
			if (Numbered)
			{
				string strRowNumber = (e.RowIndex + 1).ToString();

				while (strRowNumber.Length < this.RowCount.ToString().Length) strRowNumber = "0" + strRowNumber;
				SizeF size = e.Graphics.MeasureString(strRowNumber, this.Font);
				if (this.RowHeadersWidth < (int)(size.Width + 20)) this.RowHeadersWidth = (int)(size.Width + 20);
				Brush b = SystemBrushes.ControlText;
				e.Graphics.DrawString(strRowNumber, this.Font, b, e.RowBounds.Location.X + 15, e.RowBounds.Location.Y + ((e.RowBounds.Height - size.Height) / 2));
			}

			base.OnRowPostPaint(e);
		}
	}
}
